<template>
  <div>
    <jiazai />
    <div style="width: 100%; height: 100%;">
      <el-drawer v-model="drawer" title="I am the title" :with-header="false">
        <el-form ref="editForm" :model="editData" label-width="100px">
          <el-form-item label="姓名">
            <el-input v-model="editData.name"></el-input>
          </el-form-item>
          <el-form-item label="年龄">
            <el-input v-model="editData.age"></el-input>
          </el-form-item>
          <el-form-item label="性别">
            <el-select v-model="editData.nan">
              <el-option label="男" value="男"></el-option>
              <el-option label="女" value="女"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="日期">
            <el-date-picker
              v-model="editData.rq"
              type="date"
              placeholder="选择日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="地址">
            <el-input
              v-model="editData.dizi"
              placeholder="请输入地址"
            ></el-input>
          </el-form-item>
        </el-form>
      </el-drawer>
      <el-drawer
        v-model="drawer1"
        title="I am the title"
        direction="ttb"
        size="50%"
        :with-header="false"
      >
        <el-form ref="editForm" :model="newData" label-width="100px">
          <el-form-item label="姓名">
            <el-input v-model="newData.name"></el-input>
          </el-form-item>
          <el-form-item label="年龄">
            <el-input v-model="newData.age"></el-input>
          </el-form-item>
          <el-form-item label="性别">
            <el-select v-model="newData.nan">
              <el-option label="男" value="男"></el-option>
              <el-option label="女" value="女"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="日期">
            <el-date-picker
              v-model="newData.rq"
              type="date"
              placeholder="选择日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="地址">
            <el-input
              v-model="newData.dizi"
              placeholder="请输入地址"
            ></el-input>
          </el-form-item>
        </el-form>
        <div style="display: flex; justify-content: center; padding: 0 20px">
          <el-button type="primary" @click="saveData">保存</el-button>
          <el-button @click="drawer1 = false">取消</el-button>
        </div>
      </el-drawer>
      <div>
        <el-table-v2
          :columns="columns"
          :data="dataye"
          :width="1300"
          :height="500"
          fixed
        />
      </div>
      <div
        style="
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 0 20px;
        "
      >
        <div>
          <input
            class="search-input"
            type="text"
            v-model="searchValue"
            placeholder="请输入关键词会出现相关内容"
          />
        </div>
        <fenye
          @page-data="handlePageData"
          style="width: 742px; height: 32"
        ></fenye>
        <el-button type="primary" @click="addData">添加数据</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import jiazai from "../zi/加载中.vue";
import fenye from "./fenyeqi.vue";
import { ref, reactive, watch } from "vue";
import { computed, inject, provide, toRaw } from "vue";
import { ElMessage } from "element-plus";
import dayjs from "dayjs";
import {
  ElButton,
  ElIcon,
  ElTag,
  ElTooltip,
  TableV2FixedDir,
} from "element-plus";
import { Timer } from "@element-plus/icons-vue";

export default {
  name: "MyTable",
  components: {
    fenye,
    jiazai,
  },
  setup() {
    const isLoading = ref(false);
    provide("isLoading", isLoading);
    const editData = ref({});
    const editData1 = ref(null);
    const drawer = ref(false);
    const drawer1 = ref(false);
    const searchValue = ref(""); // 搜索关键词
    const store = inject("store");
    const count = computed(() => store.state.user);
    const su1 = ["id", "姓名", "年龄", "性别", "日期", "地址", "操作"];
    const su = ["id", "name", "age", "nan", "rq", "dizi", "operations"];
    const columns = ref(
      su.map((key, index) => ({
        key: key,
        dataKey: key,
        width: 160,
        title: su1[index],
        fixed: index === 0 ? TableV2FixedDir.LEFT : undefined,
        align: "center",
        cellRenderer: ({ cellData, column, rowData }) => {
          if (column.key === "date") {
            return (
              <ElTooltip content={dayjs(cellData).format("YYYY/MM/DD")}>
                <span class="flex items-center">
                  <ElIcon class="mr-3">
                    <Timer />
                  </ElIcon>
                  {dayjs(cellData).format("YYYY/MM/DD")}
                </span>
              </ElTooltip>
            );
          } else if (column.key === "operations") {
            const cre = () => {
              editData.value = rowData;
              drawer.value = !drawer.value;
            };
            const chanchu = () => {
              // console.log(rowData, "shanchu");
              const index = data.value.findIndex(
                (item) => item.id === rowData.id
              )
              if (index !== -1) {
                data.value.splice(index, 1);
                store.commit("datauser", data.value);
                ElMessage({
                  type: "success",
                  message: "删除成功",
                });
              }
            };
            return (
              <>
                <ElButton size="small" onClick={() => cre()}>
                  编辑
                </ElButton>
                <ElButton size="small" type="danger" onClick={() => chanchu()}>
                  删除
                </ElButton>
              </>
            );
          } else {
            return <ElTag>{cellData}</ElTag>;
          }
        },
      }))
    );
    watch(
      editData,
      () => {
        const daterq = new Date(editData.value.rq);
        let shudata = dayjs(daterq).format("YYYY-MM-DD");
        editData.value.rq = shudata;
        store.commit("datauser", data.value);
        // console.log(editData.value);
      },
      { deep: true }
    );
    const data = ref(count.value);

    const dataye = ref(data.value.slice(0, 10));

    function handlePageData(dataye1) {
      dataye.value = dataye1;
    }
    const newData = ref({
      id: "",
      name: "",
      age: "",
      nan: "",
      parentId: null,
      rq: "2022-01-01",
      dizi: "",
      operations: "",
    });
    const addData = () => {
      drawer1.value = !drawer1.value;
      // data.value.unshift(newData);
    };

    const searchResult = computed(() => {
      // 根据关键词过滤数据
      return data.value.filter((item) =>
        Object.values(item).some((value) =>
          String(value).includes(searchValue.value)
        )
      );
    });
    function saveData() {
      const daterq = new Date(newData.value.rq);
      let shudata = dayjs(daterq).format("YYYY-MM-DD");
      newData.value.rq = shudata;
      const maxId = ref(
        count.value.reduce((prev, current) => {
          return prev.id > current.id ? prev : current;
        })
      );
      newData.value.id = maxId.value.id + 1;
      if (
        Boolean(newData.value.name) &&
        Boolean(newData.value.age) &&
        Boolean(newData.value.dizi) &&
        Boolean(newData.value.nan)
      ) {
        isLoading.value = true;
        setTimeout(() => {
          drawer1.value = false;
          isLoading.value = false;
          let shu = toRaw(newData.value);
          let obj = {
            id: shu.id,
            name:shu.name,
            age: shu.age,
            nan: shu.nan,
            parentId: null,
            rq: "2022-01-01",
            dizi: shu.dizi,
            operations: "",
          };
          data.value.unshift(obj);
          store.commit("datauser", data.value);
          ElMessage({
            type: "success",
            message: "添加成功",
          });
        }, 1000);

        // console.log(newData.value);
      } else {
        ElMessage({
          type: "warning",
          message: "请填写完整",
        });
      }
      // console.log(newData);
      // console.log();
      // console.log(shudata);
      // 保存表单数据的逻辑
      // 清空表单数据
      // newData.value = {
      //   name: '',
      //   age: '',
      //   nan: '',
      //   rq: '',
      //   dizi: ''
      // };

      // 关闭抽屉
      // this.drawer1 = false;
    }
    provide("data", searchResult);

    return {
      editData,
      searchValue,
      searchResult,
      columns,
      data,
      addData,
      dataye,
      handlePageData,
      drawer,
      drawer1,
      saveData,
      editData1,
      newData,
    };
  },
};
</script>

<style lang='less' scoped>
.search-input {
  width: 200px;
  height: 36px;
  padding: 0 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
  color: #606266;
  transition: border-color 0.2s;
  &:focus {
    border-color: #409eff;
  }
  &::placeholder {
    color: #c0c4cc;
  }
}
</style>
